import React, { Component } from 'react'
import { Comment, Tooltip, List, Icon, Avatar, Form, Button, Input, Divider, message } from 'antd'
import moment from 'moment'
import { history } from 'umi'
import { getArticleCommentById, addArticleComment, updateCommentPrefer } from '@/services/detail'
import './index.less'
const { TextArea } = Input
const avatarArr = [
  'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fup.enterdesk.com%2Fedpic%2Fa2%2F20%2F77%2Fa22077cf0c937330544a02ea28c75fa3.jpg&refer=http%3A%2F%2Fup.enterdesk.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1648176236&t=9b7386b83a65a57fded3d8d2b61a730b',
  'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fup.enterdesk.com%2Fedpic_360_360%2Fc8%2F5d%2F59%2Fc85d595ed206fa63bb7bc7d7d9d17353.jpg&refer=http%3A%2F%2Fup.enterdesk.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1648176236&t=aa533f18850d5ae9740e4fdd301ae8c6',
  'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Finews.gtimg.com%2Fnewsapp_bt%2F0%2F13939871049%2F1000.jpg&refer=http%3A%2F%2Finews.gtimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1648187871&t=337e999cc1c642bede547570d707e18f',
  'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Finews.gtimg.com%2Fnewsapp_bt%2F0%2F13918837664%2F641.jpg&refer=http%3A%2F%2Finews.gtimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1648187871&t=cbdfe7f09c289802b2c230fc1f4a0bd3',
  'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Finews.gtimg.com%2Fnewsapp_bt%2F0%2F13925569686%2F641.jpg&refer=http%3A%2F%2Finews.gtimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1648187871&t=4e54a470c0995893e411c1726c2cbd6a',
  'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Finews.gtimg.com%2Fnewsapp_bt%2F0%2F13302548523%2F641.jpg&refer=http%3A%2F%2Finews.gtimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1648198141&t=6e95dfeafbfbede3f726a0329fa19514',
  'https://img1.baidu.com/it/u=79620508,1272333&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=499',
  'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201903%2F02%2F20190302143609_CFfMS.thumb.400_0.jpeg&refer=http%3A%2F%2Fb-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1648187948&t=10248c7102d80f184c44a24ff9f74ffa',
  'https://gimg2.baidu.com/image_search/src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20190816%2F7dd8046be3ed40ef8ec434b27ba3b6af.jpeg&refer=http%3A%2F%2F5b0988e595225.cdn.sohucs.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1648187948&t=31e71e9f2db231910dd34ada38fe7a53',
]

class Index extends Component {
  state = {
    comments: [],
    submitting: false,
    avatar: avatarArr[moment(new Date()).unix() % 9],
    id: '',
    updated: false,
  }
  componentDidMount() {
    this.getArticleCommentById()
  }
  componentDidUpdate() {
    this.getArticleCommentById()
  }

  // 根据文章Id获取文章信息
  getArticleCommentById = async () => {
    const nowPath = history?.location?.pathname
    const id = nowPath.replace(/[^0-9]/gi, '')
    if (id != this.state.id || this.state.updated) {
      const res = await getArticleCommentById(id)
      const comments = res.data.filter((item) => item.status === 1)
      comments.map((item, index) => {
        item.prefer = 0
        item.actions = [
          <span key="comment-basic-like" onClick={() => this.handlePrefer(item.id, 'like')} style={{ color: 'orange' }}>
            <Icon type="like" theme="filled" />
            {' ' + item.liked}
          </span>,
          <span
            key="comment-basic-dislike"
            onClick={() => this.handlePrefer(item.id, 'dislike')}
            style={{ color: 'gray' }}
          >
            <Icon type="dislike" theme="filled" />
            {' ' + item.disliked}
          </span>,
        ]
        item.datetime = (
          <Tooltip title={moment(item.add_time * 1000).format('YYYY-MM-DD HH:mm:ss')}>
            <span>
              {moment(item.add_time * 1000)
                .subtract(1, 'days')
                .fromNow()}
            </span>
          </Tooltip>
        )
      })
      this.setState({ id, comments, updated: false })
    }
  }

  // 点赞或踩赞
  handlePrefer = async (id, keywords) => {
    await updateCommentPrefer(id, keywords)
    await this.setState({ updated: true })
    this.getArticleCommentById()
  }

  // 提交评论
  handleSubmit = async (e) => {
    e.preventDefault()
    this.setState({ submitting: true })
    this.props.form.validateFields(async (err, { author, content }) => {
      if (!err) {
        const { id, avatar } = this.state
        const res = await addArticleComment(id, author, content, avatar)
        if (res?.status === 200) {
          message.success('提交成功,等待管理员审核')
          this.props.form.resetFields()
        }
      }
    })
    setTimeout(() => {
      this.setState({ submitting: false })
    }, 300)
  }
  render() {
    const { comments, submitting, avatar } = this.state
    const { getFieldDecorator } = this.props.form
    return (
      <div className="comment-div">
        {/* 添加评论 */}
        <Divider>发表评论</Divider>
        <Comment
          avatar={<Avatar src={avatar} style={{ marginTop: 5 }} />}
          content={
            <Form onSubmit={this.handleSubmit} className="comment-form">
              <Form.Item>
                {getFieldDecorator('author', {
                  rules: [{ required: true, message: '请填写你的用户名' }],
                })(<Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="用户名" />)}
              </Form.Item>
              <Form.Item>
                {getFieldDecorator('content', {
                  rules: [{ required: true, message: '评论不能为空' }],
                })(<TextArea rows={4} placeholder="请写下你的评论..." />)}
              </Form.Item>
              <Form.Item>
                {getFieldDecorator('button')(
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="comment-form-button"
                    loading={submitting}
                    type="danger"
                  >
                    发布
                  </Button>,
                )}
              </Form.Item>
            </Form>
          }
        />
        <Divider>优质评论</Divider>
        <List
          className="comment-list"
          itemLayout="horizontal"
          dataSource={comments}
          renderItem={(item) => (
            <li key={item.id}>
              <Comment
                actions={item.actions}
                author={item.author}
                avatar={item.avatar}
                content={item.content}
                datetime={item.datetime}
              />
            </li>
          )}
        />
      </div>
    )
  }
}

const WrappedComment = Form.create({ name: 'comment-form' })(Index)
export default WrappedComment
